/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.ui.page.chat;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.MessageActivity;
import com.shwread.android.qysw10000136.R;
import com.shwread.android.ui.customview.QYViewPager;
import com.shwread.android.ui.page.AbstractUIPage;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryLastUnReadMsgAction;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.geometerplus.android.util.QyreaderPerferencesUtil;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;
import logic.constants.DefaultConsts;


/**
 * 即时通讯
 * @Project： qysw_1.1.6_association
 * @Title：ChatTabPage
 * @Description：
 * @Author：wayne
 * @Date：2015年11月26日下午10:09:39
 */
public class ChatTabPage
		extends
		AbstractUIPage<MainActivity>
		implements
		OnPageChangeListener,
		OnClickListener
{
	public static final int                          TAG_SESSION  = 0;
	public static final int                          TAG_CONTACTS = 1;
	public static final int                          TAG_MOMENTS  = 2;

	private int                                      pageSelected = TAG_SESSION;

	private SessionPage                              sessionPage;
	private ContactsPage contactsPage;
	private MomentsPage                              momentsPage;

	private TextView                                 tvTitle;
	//	private TextView                                 btnCreateTeam;
	private ImageView 									 ivPersion;
	//	private Button											 btnAdd;
	private View                                     messageLayout;
	private ImageView                                ivMsgUnread;
	private ImageView                                ivUnread;

	private QYViewPager                              vpPager;
	private View                                     vTab1;
	private View                                     vTab2;
	private View                                     vTab3;
	private AbstractUIPage<MainActivity>             page;

	public static List<AbstractUIPage<MainActivity>> pages;
	private static Adapter                           pagerAdapter;

	public static ChatTabPage                        instance;
	private static long lastTimeStamp = 0;
	private ImageView iVMsgIcom;

	public ChatTabPage(MainActivity t) {
		super(t);
	}

	public static ChatTabPage getInstance(MainActivity t) {
		if (instance == null) instance = new ChatTabPage(t);
		return instance;
	}

	public static void destroy() {
		if (instance != null)
		{
			clearPage();
			instance.dispose();
			instance = null;
		}
	}

	public static void clearPage() {
		if (null != pages && pages.size() > 0)
		{
			for (AbstractUIPage page : pages)
			{
				System.out.println("ChatTabPage -->" + page.getClass().getSimpleName() + " -- dispose!!");
				page.dispose();
			}
			pages.clear();
		}
		pages = null;
	}

	public int getPageSelected() {
		return pageSelected;
	}

	public void setPageSelected(int pageSelected) {
		this.pageSelected = pageSelected;
	}

	@Override
	public <E extends Activity> View createView(E arg0, int arg1) {
		if (null != curMyView) return curMyView;
		curMyView = bActivity.getLayoutInflater().inflate(R.layout.chat_tab_layout, null);
		lastTimeStamp = QyreaderPerferencesUtil.getInstance(context, "0").getLastMsgTimeStamp();
		findViews();
		initPage();
		setListeners();
		return curMyView;
	}

	void findViews() {
		vpPager = (QYViewPager) curMyView.findViewById(R.id.chat_pager);
		vTab1 = curMyView.findViewById(R.id.chat_tab_session);
		vTab2 = curMyView.findViewById(R.id.chat_tab_contacts);
		vTab3 = curMyView.findViewById(R.id.chat_tab_moments);
		tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
		tvTitle.setText(R.string.maintab_chat);

		ivPersion = (ImageView) curMyView.findViewById(R.id.common_header_persion);
		ivPersion.setVisibility(View.VISIBLE);
//		btnCreateTeam = (TextView) curMyView.findViewById(R.id.common_header_create_team);
//		btnCreateTeam.setVisibility(View.VISIBLE);

		//		btnSearch = (Button) curMyView.findViewById(R.id.common_header_search);
		//		btnSearch.setVisibility(View.VISIBLE);
		//		btnAdd = (Button) curMyView.findViewById(R.id.common_header_persion);
		//		btnAdd.setBackgroundResource(R.drawable.ic_chat_add);
		//		btnAdd.setVisibility(View.VISIBLE);
		// 显示未读消息的layout
		messageLayout = curMyView.findViewById(R.id.common_header_msg_layout);
		messageLayout.setVisibility(View.VISIBLE);
		messageLayout.setOnClickListener(this);
		// 未读消息小红点
		ivMsgUnread = (ImageView) curMyView.findViewById(R.id.common_header_msg_unread_flag);
		ivUnread = (ImageView) curMyView.findViewById(R.id.monment_msg_unread_flag);
		ivUnread.setVisibility(View.GONE);
		iVMsgIcom = (ImageView) curMyView.findViewById(R.id.iVMsgIcom);
		pagerAdapter = new Adapter();
	}

	private void setListeners() {
		vTab1.setOnClickListener(this);
		vTab2.setOnClickListener(this);
		vTab3.setOnClickListener(this);
		vpPager.setSliding(false);
		vpPager.setOnPageChangeListener(this);
//		btnCreateTeam.setOnClickListener(new OnClickListener()
//		{
//			@Override
//			public void onClick(View v) {
//				//创建群组
//				Intent creatTeamIntent = new Intent(context, NewInteractionCreateTeamChMActivity.class);
//				creatTeamIntent.putExtra(DefaultConsts.NI_CONTACT_INTENT, DefaultConsts.NI_CONTACT_CREATE_TEAM);
//				bActivity.startActivityForResult(creatTeamIntent, MainTabFragment.CREATE_TEAM);
//			}
//		});
		ivPersion.setOnClickListener(this);
	}

	private void initPage() {
		pages = new ArrayList<AbstractUIPage<MainActivity>>();

		sessionPage = SessionPage.getInstance(bActivity);
		contactsPage = ContactsPage.getInstance(bActivity);//老的通讯录
		momentsPage = MomentsPage.getInstance(bActivity);

		pages.add(sessionPage);
//		pages.add(contactsPage);//老通讯录打开着句，去掉下一句
//		pages.add(ContactsPage.getInstance(bActivity));//老通讯录
		pages.add(LayereContactsPage.getInstance(bActivity));//分层通讯录
		pages.add(momentsPage);

		vpPager.setAdapter(pagerAdapter);
		pagerAdapter.notifyDataSetChanged();
		setDefaultPage(pageSelected);
	}

	private void setDefaultPage(int type) {
		vTab1.setSelected(true);
		sessionPage.createView(bActivity, DEFAULT_STATUS);
		vpPager.setCurrentItem(TAG_SESSION);
	}

	@Override
	public int enter(IUIPage<?> arg0) {
		onSelected(pageSelected);
		qryUnReadTotal();
		return 0;
	}

	@Override
	public int leave(IUIPage<?> arg0) {
		return 0;
	}

	@Override
	public void notifyView(int arg0, Bundle arg1) {
		switch (arg0) {
			case DefaultConsts.PAGE_ONRESUME_CODE:
				qryUnReadTotal();
				break;
			//			case DefaultConsts.MESSAGE_UNREAD_CHANGE_CODE:
			//				boolean res = arg1.getBoolean("result");
			//				ivMsgUnread.setVisibility(res ? View.VISIBLE : View.GONE);
			//				break;
			//			case BaseBusinessActivity.COMMENTS_REQUEST_CODE:
			//				//互动中心评论发送成功
			//				//				Utils.showToast(bActivity, "互动中心评论成功");
			//				contentItemView.updateComment(arg1.getInt("position"), arg1.getInt("count"));
			//				break;
			//			case DefaultConsts.START_PUBLISH_THEME_ACTIVITY:
			//				contentItemView.getInteractionData(1);
			//				break;
		}
	}

	@Override
	public void setStatus(int arg0) {

	}

	@Override
	public View updateView(int arg0, ITaskResult arg1) {
		return null;
	}

	private void qryUnReadTotal() {
//		new QryUnReadTotalAction(bActivity, DefaultConsts.TYPE_WRITESOURCE_ENTERPRISE, new GetUnreadAction(true)).start();
//		new QryUnReadTotalAction(bActivity, DefaultConsts.TYPE_WRITESOURCE_SYSTEM, new GetUnreadAction(false)).start();
		if(lastTimeStamp==0){
			new QryLastUnReadMsgAction(bActivity, "",System.currentTimeMillis()+"", new GetLastMsgUnreadAction()).start();
		}else{
			new QryLastUnReadMsgAction(bActivity, "",lastTimeStamp+"", new GetLastMsgUnreadAction()).start();
		}
	}

	private Integer tempE = null, tempS = null;


	private class GetLastMsgUnreadAction
			extends
			BaseAction
	{

		@Override
		public void OK(Object obj) {
			Log.e("消息", "OK: "+obj.toString() );
			JSONObject jsonObject = (JSONObject) obj;
			try {
				QyreaderPerferencesUtil.getInstance(context, "0").setLastMsgTimeStamp(jsonObject.getLong("lastTimeStamp"));
				final int msgType = jsonObject.getInt("msgType");
				bActivity.getUIHandler().post(new Runnable()
				{
					@Override
					public void run() {
						if (msgType ==1003){//无消息
							iVMsgIcom.setImageResource(R.drawable.iconfont_xiaoxi);
							ivMsgUnread.setVisibility(View.GONE);
						}else if(msgType ==1002){//系统消息
							iVMsgIcom.setImageResource(R.drawable.has_new_sys);
							ivMsgUnread.setVisibility(View.VISIBLE);
						}else if(msgType ==1001){//企业消息
							iVMsgIcom.setImageResource(R.drawable.has_new_ent);
							ivMsgUnread.setVisibility(View.VISIBLE);
						}
					}
				});
			} catch (JSONException e) {
				e.printStackTrace();
			}
//			{"resultCode":1000,"returnObject":{"lastTimeStamp":1477363606938,"msgType":1003}}
//			final int count = (Integer) obj;
////			if (flag)
////			{
////				// if(count>0) Const.UNREAD_MSG_COUNT_E = count;
////				tempE = count;
////			}
////			else
////			{
////				// if(count>0) Const.UNREAD_MSG_COUNT_S = count;
////				tempS = count;
////			}
//			if (tempE != null && tempS != null)
//			// if (Const.UNREAD_MSG_COUNT_E != null && Const.UNREAD_MSG_COUNT_S
//			// != null)
//			{
//				bActivity.getUIHandler().post(new Runnable()
//				{
//					@Override
//					public void run() {
//						boolean res = (tempE == 0 && tempS == 0) ? false : true;
//						// boolean res = (Const.UNREAD_MSG_COUNT_E == 0 &&
//						// Const.UNREAD_MSG_COUNT_S == 0) ? false : true;
//						ivMsgUnread.setVisibility(res ? View.VISIBLE : View.GONE);
//					}
//				});
//			}
		}
	}

//	private class GetUnreadAction
//			extends
//			BaseAction
//	{
//		boolean flag;
//
//		public GetUnreadAction(boolean flag) {
//			this.flag = flag;
//		}
//
//		@Override
//		public void OK(Object obj) {
//			final int count = (Integer) obj;
//			if (flag)
//			{
//				// if(count>0) Const.UNREAD_MSG_COUNT_E = count;
//				tempE = count;
//			}
//			else
//			{
//				// if(count>0) Const.UNREAD_MSG_COUNT_S = count;
//				tempS = count;
//			}
//			if (tempE != null && tempS != null)
//			// if (Const.UNREAD_MSG_COUNT_E != null && Const.UNREAD_MSG_COUNT_S
//			// != null)
//			{
//				bActivity.getUIHandler().post(new Runnable()
//				{
//					@Override
//					public void run() {
//						boolean res = (tempE == 0 && tempS == 0) ? false : true;
//						// boolean res = (Const.UNREAD_MSG_COUNT_E == 0 &&
//						// Const.UNREAD_MSG_COUNT_S == 0) ? false : true;
//						ivMsgUnread.setVisibility(res ? View.VISIBLE : View.GONE);
//					}
//				});
//			}
//		}
//	}

	private class Adapter
			extends
			PagerAdapter
	{

		@Override
		public int getCount() {

			return pages == null ? 0 : pages.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {

			return arg0 == arg1;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {

			AbstractUIPage<MainActivity> page = pages.get(position);

			if (page.getView() == null)
			{
				page.createView(bActivity, DEFAULT_STATUS);
			}

			if (page.getView().getParent() == null)
			{
				container.addView(page.getView());
			}

			return page.getView();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
		}

	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageSelected(int arg0) {
		onSelected(arg0);

	}

	private void onSelected(int select) {
		clickTab(select);
		pageSelected = select;
		page = pages.get(pageSelected);
		page.enter(null);
	}

	private void clickTab(int select) {
		vTab1.setSelected(select == TAG_SESSION ? true : false);
		vTab2.setSelected(select == TAG_CONTACTS ? true : false);
		vTab3.setSelected(select == TAG_MOMENTS ? true : false);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_msg_layout:
				bActivity.startActivity(new Intent(bActivity, MessageActivity.class));
				break;
			case R.id.chat_tab_session:
				setSelectPage(TAG_SESSION);
				break;
			case R.id.chat_tab_contacts:
				setSelectPage(TAG_CONTACTS);
				break;
			case R.id.chat_tab_moments:
				setSelectPage(TAG_MOMENTS);
				ivUnread.setVisibility(View.GONE);
				break;
			case R.id.common_header_persion:
				bActivity.goPersonalActivity();
				break;
			default:
				break;
		}

	}

	public void setSelectPage(int select) {
		if (pageSelected != select)
		{
			vpPager.setCurrentItem(select);
		}
	}
}
